<?php
FLEA::loadClass('TMIS_Controller');
class Controller_Chengpin_Dye_CpMdZyCk extends Tmis_Controller {
    var $_modelExample;
    var $funcId;
    function Controller_Chengpin_Dye_CpMdZyCk() {
        $this->_modelOrder = & FLEA::getSingleton('Model_Trade_Dye_Order');
        $this->_modelOrder2Ware = & FLEA::getSingleton('Model_Trade_Dye_Order2Ware');
        $this->_modelExample = & FLEA::getSingleton('Model_Chengpin_Dye_Cpck');
        $this->_modelClient = & FLEA::getSingleton('Model_JiChu_Client');
        $this->_modelGang = & FLEA::getSingleton('Model_Plan_Dye_Gang');
        $this->_modelExampleDb = & FLEA::getSingleton('Model_Chejian_DabaoChanliang');
        $this->_modelPrintLog = & FLEA::getSingleton('Model_Chengpin_Printblog');
        $this->_kind = '码单出库';

        $this->fldMain = array(
            'chukuCode' => array('title' => '出库单号', "type" => "text", 'readonly' => true,'value' =>'自动生成' ),
            'chukuDate' => array('title' => '出库日期', 'type' => 'calendar', 'value' => date('Y-m-d')),
            'kind' => array('title'=>'出库类型','type' => 'text', 'value' => $this->_kind,'readonly'=>true),
            'planIdA' => array(
                'title' => '选择缸号', 
                'type' => 'popup', 
                'value' => '',
                'name'=>'planIdA',
                'text'=>'',
                'url'=>url('Plan_Dye','PopupGang'),//PopupW
                //'jsTpl'=>'Cangku/Chengpin/jsRuku.tpl',//需要载入的模板文件，这个文件中不需要使用{literal},因为是通过file_get_content获得的
                'onSelFunc'=>'onSel',//选中后需要执行的回调函数名,需要在jsTpl中书写
                'textFld'=>'vatNum',//显示在text中的字段
                'hiddenFld'=>'planIdA',//显示在hidden控件中的字段
                'isMd'     =>true
            ),
            // 'memo'=>array('title'=>'备注','type'=>'textarea','name'=>'memo'),
            // 下面为隐藏字段
            'creater' => array('type' => 'hidden', 'value' => $_SESSION['REALNAME']),
        );
        // /从表表头信息
        // /type为控件类型,在自定义模板控件
        // /title为表头
        // /name为控件名
        // /bt开头的type都在webcontrolsExt中写的,如果有新的控件，也需要增加
        $this->headSon = array(
            '_edit' => array('type' => 'btBtnDelete', "title" => '操作', 'name' => '_edit[]'),
            'orderCode'=>array('type'=>'BtText',"title"=>'订单编号','name'=>'orderCode[]','readonly'=>true),
            'vatNum'=>array('type'=>'BtText',"title"=>'缸号','name'=>'vatNum[]','readonly'=>true),
            // 'dabaoCode'=>array('type'=>'BtText',"title"=>'打包单号','name'=>'dabaoCode[]','readonly'=>true),
            'wareId'=>array('type'=>'BtHidden','name'=>'wareId[]','readonly'=>true),
            'proName'=>array('type'=>'BtText',"title"=>'纱支规格','name'=>'proName[]','readonly'=>true),
            'color'=>array('type'=>'BtText',"title"=>'颜色','name'=>'color[]','readonly'=>true),
            'colorNum' => array('type' => 'BtText', "title" => '色号', 'name' => 'colorNum[]','readonly'=>true),
            'cntTongzi' => array('type' => 'BtText', "title" => '筒子数', 'name' => 'cntTongzi[]','readonly'=>true),
            'cnt' => array('type' => 'BtText', "title" => '出库数量', 'name' => 'cnt[]','readonly'=>true),
            'cntJuan' => array('type' => 'BtText', "title" => '出库卷数', 'name' => 'cntJuan[]','readonly'=>true),
            'Madan' => array('type' => 'btBtnMadan', "title" => '码单', 'name' => 'Madan[]'),
            // 'memoView' => array('type' => 'BtText', "title" => '备注', 'name' => 'memoView[]'),
            'memo'=>array('title' => '备注','type' => 'btselect','value' =>'','name'=>'memo[]','options'=>array(
                    array('text'=>'不结账','value'=>'不结账'),
                    array('text'=>'未发完','value'=>'未发完'),
                    array('text'=>'已发完','value'=>'已发完'),
                    array('text'=>'退回回修','value'=>'退回回修'),
                    array('text'=>'退回回倒','value'=>'退回回倒'),
                    array('text'=>'退回检纱','value'=>'退回检纱'),
                    array('text'=>'未完经纱','value'=>'未完经纱'),
                )),
            // ***************如何处理hidden?
            'id' => array('type' => 'BtHidden', 'name' => 'id[]'),
            'cntM' => array('type' => 'BtHidden', 'name' => 'cntM[]'),
            'danjia' => array('type' => 'BtHidden', 'name' => 'danjia[]'),
            'orderId' => array('type' => 'BtHidden', 'name' => 'orderId[]'),
            'ord2proId' => array('type' => 'BtHidden', 'name' => 'ord2proId[]'),
            'gangId' => array('type' => 'BtHidden', 'name' => 'gangId[]'),
            'cntDz' => array('type' => 'BtHidden', 'name' => 'cntDz[]'),
            'chanliangId' => array('type' => 'BtHidden', 'name' => 'chanliangId[]'),
        );
        $this->sonTpl = array(
            'Cangku/choose.tpl'
        );
    }

    #列表
    function actionRight() {
        $this->authCheck(75);
        FLEA::loadClass('TMIS_Pager');
        TMIS_Pager::clearCondition();
        $arr = TMIS_Pager::getParamArray(array(
            'dateFrom' =>date("Y-m-d",mktime(0,0,0,date("m"),date("d")-360,date("Y"))),
            'dateTo' => date("Y-m-d"),
            'clientId'=>'',
            'vatNum'=>'',
            'orderCode'=>''
        ));

        $sql = "SELECT
                x.*
            FROM
                view_dye_gang x
            WHERE 1
            AND NOT EXISTS(SELECT * FROM plan_dye_gang a WHERE a.parentGangId = x.gangId AND a.isHuixiuCk=1)";
        if ($arr[dateFrom]) {
            $sql .=" AND x.planDate >= '$arr[dateFrom]' AND x.planDate <= '$arr[dateTo]'";
        }
        if ($arr['clientId']!='') $sql .=" and x.clientId='$arr[clientId]'";
        if ($arr['vatNum']!='') $sql .=" and x.vatNum like '%$arr[vatNum]%'";
        if ($arr['orderCode']!='') $sql .=" and x.orderCode like '%$arr[orderCode]%'";
        $sql .= " ORDER BY x.gangId DESC ";
        // dump($sql);die;
        $pager = new TMIS_Pager($sql,null,null,400);
        $rowset = $pager->findAllBySql($sql);
        if(count($rowset)>0) foreach($rowset as & $v) {
            $v['guige']=$v['wareName']." ".$v['guige'];
            $v['cntChuku'] = $this->_modelGang->getCpckChanliang($v[gangId]);
            $v['_edit']="<a href='".$this->_url('Add',array(
                //'gangId'=>$v['gangId']
                'orderId'=>$v['orderId']
                //'ordwarId'=>$v['order2wareId']
            ))."'>出库</a>";

            //得到客户单号
            $clientCode=$this->_modelOrder->find(array('id'=>$v['orderId']));
            if($clientCode['orderCode2']!='') $v['compName']=$v['compName'].'('.$clientCode['orderCode2'].')';
        }
        $arr_field_info = array(
            'planDate' => '计划日期',
            'vatNum' => '缸号',
            'orderCode' => '订单号',
            'compName' => '客户(客户单号)',
            'guige' => '纱支',
            'color' => '颜色',
            'colorNum' => '色号',
            'cntPlanTouliao' => '计划投料',
            'planTongzi' => '计划筒子数',
            'cntChuku' => '已出库',
            '_edit' => '操作'
        );
        $smarty = & $this->_getView();
        $smarty->assign("arr_field_info",$arr_field_info);
        $smarty->assign('arr_field_value',$rowset);
        if ($pager!=null) $smarty->assign('page_info',$pager->getNavBar($this->_url('addGuide',$arr)));
        $smarty->assign('arr_condition',$arr);
        $smarty->display('TableList.tpl');
    }
    

    #列表
    function actionRightMd() {
        //$this->funcId = 75;               //成品-出库-查询
        $this->authCheck(75);
        //$table = $this->_modelExample->tableName;
        FLEA::loadClass('TMIS_Pager');
        //TMIS_Pager::clearCondition();
        $arr = TMIS_Pager::getParamArray(array(
            dateFrom=>date("Y-m-d",mktime(0,0,0,date("m"),date('d')-30,date("Y"))),
            dateTo=>date("Y-m-d"),
            clientId=>0,
            vatNum=>'',
            zhishu=>'',
            'color'=>'',
            isReport=>0,
            'chukuCode'=>''
        ));
        //if ($arr[isReport]==1) $arr['clientId'] = $_POST[clientId]?$_POST[clientId]:$_GET[clientId];
        $str = "select
            x.*,
            y.compName,y.orderCode,y.vatNum,y.wareName,y.guige,y.color,y.vatCode,y.cntPlanTouliao,y.orderId,
            concat(y.guige,' ',y.wareName) as zhishu,y.clientId
            from chengpin_dye_cpck x
            inner join view_dye_gang y on x.planId=y.gangId
            where x.kind='码单出库' and ";

        $condition=array();
        if ($arr[dateFrom]) {
            //echo($arr[dateTo]);
            $condition[] = "date(x.dateCpck)>='$arr[dateFrom]'";
            $condition[] = "date(x.dateCpck)<='$arr[dateTo]'";
        }
        if ($arr[vatNum]!='') {
            $condition[] = "y.vatNum like '%$arr[vatNum]%'";
        }
        //if ($arr[zhishu]!='') $condition[] = "y.guige like '%$arr[zhishu]%'";
        if ($arr['color']!='') $condition[] = "y.color like '%$arr[color]%'";
        if ($arr['chukuCode']!='') $condition[] = "x.chukuCode like '%$arr[chukuCode]%'";
        if ($arr['clientId']>0) $condition[] = "y.clientId='$arr[clientId]'";
        // $condition[] = "x.kind = 0 ";
        $str .= join(" and ",$condition);
        $str .= " order by chukuCode DESC,dt DESC";
        //重新构造一个sql 让zhushu 能进行搜索
        $sql = "select * from ($str) as a where 1";
        if ($arr[zhishu]!='') $sql .= " and a.zhishu like '%$arr[zhishu]%'";
        //echo $str;
        $pager =& new TMIS_Pager($sql,null,null,200);
        $rowset = $pager->findAllBySql($sql);
        //dump($rowset[0]);
        foreach($rowset as & $value) {
            $sql = "select count(*) cnt from chengpin_blog2cpck where cpckId={$value['id']}";
            $re = mysql_fetch_assoc(mysql_query($sql));
            if($re['cnt']>0) {
            $value['_bgColor'] ='#cccccc';
            }
            //dump($value);
            $tTouliao += $value[cntPlanTouliao];
            $jingKg += $value[jingKg];
            $jingKgZ += $value[jingKgZ];
            $cntChuku += $value[cntChuku];
            $cntJian += $value[cntJian];
            $cntTongzi += $value[cntTongzi];
            $value[guige] =$value[guige]." ".$value[wareName];
            //dump($value[guige]);exit;
            $value[orderCode]=$this->_modelOrder->getOrderTrack($value[orderId],$value[orderCode]);
            //得到客户单号
            $clientCode=$this->_modelOrder->find(array('id'=>$value['orderId']));
            if($clientCode['orderCode2']!='') $value['compName']=$value['compName'].'('.$clientCode['orderCode2'].')';
            $value['edit'] = "<a href='".$this->_url('Edit',array('chukuCode'=>$value['chukuCode'],))."'>修改</a>" . ' ' . $this->getRemoveHtml($value['id']);
            $value['edit'] .=" <a href='".$this->_url('MadanInfo',array('id'=>$value['id']))."'>码单</a>  ";
        }
        //dump($rowset[0]);
        $i = count($rowset);
        $rowset[$i][dateCpck]="<b>合计</b>";
        $rowset[$i][cntPlanTouliao] = "<b>$tTouliao</b>";
        $rowset[$i][jingKg] ="<b>$jingKg</b>";
        $rowset[$i][jingKgZ] ="<b>$jingKgZ</b>";
        $rowset[$i][cntChuku] ="<b>$cntChuku</b>";
        $rowset[$i][cntJian] ="<b>$cntJian</b>";
        $rowset[$i][cntTongzi] ="<b>$cntTongzi</b>";
        //dump($rowset[0]);
        //dump($rowset[$i]);
        $smarty = & $this->_getView();
        $arrFieldInfo = array(
            "dateCpck" =>"出库日期",
            'compName' => '客户(客户单号)',
            "orderCode" =>"定单号",
            "chukuCode" =>"出库单号",
            "vatNum" =>"缸号",
            "guige" => "规格",
            "color" =>"颜色",
            "vatCode" =>"物理缸号",
            "cntPlanTouliao" =>"投料数",
            'cntChuku'=>'本次发货',
            "jingKg"=>"净重",
            "jingKgZ"=>"计价重量",
            "cntJian"=>"件数",
            "cntTongzi"=>"筒子数",
            "dt"=>"创建时间",
            'edit'=>'操作'
        );
        $smarty->assign('title','筒染成品出库');
        $smarty->assign('arr_edit_info',$arrEditInfo);
        $smarty->assign('arr_field_info',$arrFieldInfo);
        $smarty->assign('arr_field_value',$rowset);
        $smarty->assign('add_display', 'none');
        $smarty->assign('arr_condition',$arr);
        $smarty->assign('isClient',1);//是否显示客户不同 1 为是 0 为否
        $smarty->assign('page_info',$pager->getNavBar($this->_url($_GET['action'],$arr)));
        if ($arr[isReport]!=1) $smarty->display('Chengpin/Dye/CpckManage.tpl');
        else $smarty->display('TableList.tpl');
    }

    /**
     * 出库 码单模式
     * Time：2020年11月4日 14:14:42
     * @author shen
    */
    function actionAddZiyou(){
        // dump($arr['Products']);exit;
        // 从表信息字段,默认5行
        for($i = 0;$i < 1;$i++) {
            $rowsSon[] = array();
        }
        $smarty = &$this->_getView();
        $areaMain = array('title' => $this->_kind.'基本信息', 'fld' => $this->fldMain);
        $smarty->assign('areaMain', $areaMain);
        $smarty->assign('headSon', $this->headSon);
        $smarty->assign('rowsSon', $rowsSon);
        $_from = $_GET['fromAction']==''?'add':$_GET['fromAction'];
        $smarty->assign('fromAction', $_from);
        $smarty->assign('rules', $this->rules);
        $smarty->assign('sonTpl', $this->sonTpl);
        $smarty->display('Main2Son/T1.tpl');
    }

    #修改界面
    function actionEdit() {
        // dump($_GET);die;
        // if (!$this->_editable($_GET[id])) js_alert('该出库单已经被财务审核过了！您不能修改！','window.history.go(-1)');
        $arr=$this->_modelExample->find(array('chukuCode'=>$_GET['chukuCode']));
        foreach ($this->fldMain as $k => &$value) {
            $value['value'] = $arr[$k];
        }
        $this->fldMain['chukuDate']['value'] = $arr['dateCpck'];
        //出库明细
        $rows = $this->_modelExample->findAll(array('chukuCode'=>$_GET['chukuCode']));
        foreach ($rows as $key => & $v) {
            $gangInfo = $this->_modelGang->find($v['planId']);
            $v['color'] = $gangInfo['OrdWare']['color'];
            $v['vatNum'] = $gangInfo['vatNum'];
            $v['colorNum'] = $gangInfo['OrdWare']['colorNum'];
            $v['ord2proId'] = $gangInfo['OrdWare']['id'];
            $madan = array_col_values($v['Madan'],'id');
            $v['Madan'] = $madan;
            $v['Madan'] = implode(',', $v['Madan']);
            // $orderInfo = $this->_modelOrder->find($v['orderId']);
            $orderSon = $this->_modelOrder2Ware->find($v['ord2proId']);
            $v['orderCode'] = $orderSon['Order']['orderCode'];
            $v['proName'] = $orderSon['Ware']['wareName'].' '.$orderSon['Ware']['guige'];
            $dabaoInfo = $this->_modelExampleDb->find($v['chanliangId']);
            $v['dabaoCode'] = $dabaoInfo['dabaoCode'];
            $row['Products'][] = array(
                'id'=>$v['id'],
                'chanliangId'=>$v['chanliangId'],
                'orderCode'=>$v['orderCode'],
                'vatNum'=>$v['vatNum'],
                'dabaoCode'=>$v['dabaoCode'],
                'gangId'=>$v['planId'],
                'color'=>$v['color'],
                'colorNum'=>$v['colorNum'],
                'proName'=>$v['proName'],
                'cnt'    =>$v['cntChuku'],
                'cntJuan'=>$v['cntJian'],
                'cntDz'  =>$v['jingKg'],
                'Madan'=>$v['Madan'],
                'memo' =>$v['memo'],
                'cntTongzi'=>$v['cntTongzi']
            );
        }
        // dump($row);die;
        foreach($row['Products'] as &$v) {
            $temp = array();
            foreach($this->headSon as $kk => &$vv) {
                $temp[$kk] = array('value' => $v[$kk]);
            }
            $rowsSon[] = $temp;
        }
        // dump($rowsSon);die;
        // dump($this->fldMain);die;
        unset($this->fldMain['planIdA']);
        $smarty = &$this->_getView();
        $areaMain = array('title' => $this->_kind.'基本信息', 'fld' => $this->fldMain);
        $smarty->assign('areaMain', $areaMain);
        $smarty->assign('headSon', $this->headSon);
        $smarty->assign('rowsSon', $rowsSon);

        $_from = $_GET['fromAction']==''?'add':$_GET['fromAction'];
        $smarty->assign('fromAction', $_from);
        $smarty->assign('rules', $this->rules);
        $smarty->assign('sonTpl', $this->sonTpl);
        $smarty->display('Main2Son/T1.tpl');
    }

    function actionViewChoose(){
        $dabaoCode = $_GET['dabaoCode'];
        $wareId = $_GET['wareId'];
        $gangId = $_GET['gangId'];
        $ord2proId = $_GET['ord2proId'];
        $ord2proId = $_GET['ord2proId'];
        $chukuId = $_GET['chukuId'];
        if(!$gangId){
            $res = array();
        }else{
            $sql = "SELECT x.id as madanId,x.xianghao as checkID,x.maozhong as weight,x.gangId,x.chukuId,x.jingzhong as dingzhong,x.jingzhong as cntDz,x.cntTongzi
                from dye_db_chanliang_mx x
                LEFT JOIN dye_db_chanliang y on x.chanliangId=y.id
                where 1 and x.gangId='{$gangId}'";
            $res = $this->_modelExample->findBySql($sql);
        }
        foreach ($res as $key => &$value) {
            if($value['chukuId']>0&&$chukuId>0){ //修改的情况
                //该码单如果有出库id并且不是此出库单号的出库id，需要disabled
                if($value['chukuId']!=$chukuId){
                    $value['disabled'] ='true';
                }else{
                    // $value['checked'] ='true';
                }
            }elseif ($value['chukuId']>0&&!$chukuId) {
                // $value['checked'] = 'true';
                $value['disabled'] = 'true';
            }
        }

        //按照卷号进行从小到大的排序 by zhang 2017-10-25
        $flag = array();
        foreach ($res as $key => &$value) {
            $flag[] = $value['checkID'];
        }
        array_multisort($flag, SORT_ASC, $res);

        $gang= $this->_modelGang->find($gangId);
        // dump($gang);die;
        $smarty = & $this->_getView();
        $smarty->assign('res', $res);
        $smarty->assign('gang', $gang);
        $smarty->display("Cangku/ChooseSelect.tpl");
    }
    


    /**
     * 保存重写，因为这里需要处理码单信息
    */
    function actionSave(){
        // dump($_POST);exit;
        //开始保存
        $pros = array();
        $madan_clear = array();
        foreach($_POST['gangId'] as $key=>&$v) {
            if($v=='' || empty($_POST['cnt'][$key]) || $_POST['cnt'][$key]<=0) continue;
            $temp = array();
            foreach($this->headSon as $k=>&$vv) {
                //查找码单是否设置
                if($k=='Madan'){
                    $_madan=explode(',', $_POST[$k][$key]);
                    // dump($vv);exit;
                    foreach($_madan as & $cc){
                        $temp[$k][]=array('id'=>$cc);
                    }
                    // dump($temp);exit;
                }else $temp[$k] = $_POST[$k][$key];
            }
            $pros[]=$temp;
        }
        if(count($pros)==0) {
            js_alert('请选择有效的产品明细信息!','window.history.go(-1)');
            exit;
        }
        if($_POST['chukuCode']=='自动生成'){
            $_POST['chukuCode'] = $this->_getNewCode('M','chengpin_dye_cpck','chukuCode');
        }
        // dump($pros);die;
        
        foreach ($pros as $key => &$value) {
           //缸号完成标记
           if($value['memo']=='已发完'){
               $sql="update plan_dye_gang set fhWc=1 WHERE id='{$value['gangId']}'";
               $this->_modelExample->execute($sql);
           }else{
               if($value['id']){
                  //修改情况
                  $sql="SELECT * FROM chengpin_dye_cpck WHERE memo='已发完'";
                  $ck = $this->_modelExample->findBySql($sql);
                  if(!$ck){
                     $sql="update plan_dye_gang set fhWc=0 WHERE id='{$value['gangId']}'";
                     $this->_modelExample->execute($sql);
                  }
               }else{
                  $sql="update plan_dye_gang set fhWc=0 WHERE id='{$value['gangId']}'";
                  $this->_modelExample->execute($sql);
               }
               
           }
           $madanArr = array();
           $arr[] = array(
               'id'      =>$value['id'],
               'dateCpck'=>$_POST['chukuDate'],
               'planId'  =>$value['gangId'],
               'jingKg'  =>$value['cntDz'],
               'cntJian' =>$value['cntJuan'],
               'maoKg'   =>$value['cnt'],
               'cntChuku'=>$value['cnt'],
               'chukuCode'=>$_POST['chukuCode'],
               'chanliangId'=>$value['chanliangId']+0,
               'kind'     =>'码单出库',
               'memo'     =>$value['memo'],
               'cntTongzi'=>$value['cntTongzi'],
               'Madan'    =>$value['Madan']
           );
           // dump($arr);die;
           $madanArr = array_col_values($value['Madan'],'id');
           // dump(join(',',$madanArr));die;
           if($value['id']>0){
               //看看是否有需要删除的数据
               if($madanArr){
                   $sql = "update dye_db_chanliang_mx set chukuId=0 where chukuId='{$value['id']}' and id not in(".join(',',$madanArr).")";
                   // dump($sql);die;
                   $this->_modelExample->execute($sql);
               }
           }
        }
        // dump($arr);die;
        $gangIds = array_col_values($arr,'planId');
       
        if(!$this->_modelExample->saveRowset($arr)) {
            js_alert('保存失败','window.history.go(-1)');
            exit;
        }
        // dump($_POST);die;
        foreach ($gangIds as $key => &$values) {
            $this->updateFhStatus($values,$_POST['memo'][$key],$_POST['id'][$key]);
        }
        //跳转
        if($_POST['id'][0]>0){
            redirect($this->_url('RightMd'));exit();
        }else{
            redirect($this->_url('AddZiyou'));exit();
        }
    }

    //根据前缀，自动从表中产生$head.yymmddxxx的流水号
    function _getNewCode($head,$tblName,$fieldName) {
        $m = FLEA::getSingleton('Model_Acm_User');
        $sql = "select {$fieldName} from {$tblName} where {$fieldName} like '{$head}_________' order by {$fieldName} desc limit 0,1";

        $_r = $m->findBySql($sql);
        $row = $_r[0];

        $init = $head .date('ym').'00001';
        if(empty($row[$fieldName])) return $init;
        if($init>$row[$fieldName]) return $init;
        //自增1
        $max = substr($row[$fieldName],-5);
        $pre = substr($row[$fieldName],0,-5);
        // dump($pre);
        // dump(substr(100001+$max,1));die;
        return $pre .substr(100001+$max,1);
    }
    
    /**
     * 更新发货状态
     * @param  [type] $planId [description]
     * @return [type]         [description]
     */
    function updateFhStatus($planId,$memo,$id){
        // dump($planId);
        // dump($memo);die;
        if($memo=='已发完'){
            $sql="update plan_dye_gang set fhWc=1 WHERE id='{$planId}'";
            $this->_modelExample->execute($sql);
        }else{
            if($id){ //如果是修改情况，需要查看是否存在已发完的出库记录，如果存在，那么该缸不需要fhWc=0
                $sql="SELECT * FROM chengpin_dye_cpck WHERE planId='{$planId}' AND memo='已发完'";
                $ck = $this->_modelExample->findBySql($sql);
                if(!$ck){
                   // dump(11);die;
                   $sql="update plan_dye_gang set fhWc=0 WHERE id='{$planId}'";
                   $this->_modelExample->execute($sql);
                }
            }else{
                $sql="update plan_dye_gang set fhWc=0 WHERE id='{$planId}'";
                $this->_modelExample->execute($sql);
            }
        }
        //查询出此出库缸号的订单号
        $sqlOrd = "select o.id as oId,t.id as tId
                   from plan_dye_gang g 
                   left join trade_dye_order2ware t on g.order2wareId=t.id
                   left join trade_dye_order o on o.id=t.orderId
                   where 1 and g.id='{$planId}'";
        $ckRes = $this->_modelExample->findBySql($sqlOrd);
        //dump($ckRes);die;
        $sqll = "select id from trade_dye_order2ware where orderId='{$ckRes[0]['oId']}'";
        $lRes = $this->_modelExample->findBySql($sqll);
        $wRes = array();
        //dump($lRes);die;
        foreach ($lRes as $ke => &$vvv) {
            $sqlo="select * from plan_dye_gang where order2wareId='{$vvv['id']}'";
            //dump($sqlo);
            $wRes[] = $this->_modelExample->findBySql($sqlo);
        }
        //dump($wRes);die;
        $isFw = true;
        foreach ($wRes as $kk => &$vaa) {
          foreach ($vaa as $kky => &$vae) {
             if($vae['fhWc']==0){
                   $isFw =false;
                }
          }
        }
        //如果该订单下的所有缸号都已经发货完成，那么这个订单标记完成，（做这个的目的是，财务对账里的客户对账单需要显示的是该订单所有缸号都发货完成才显示）
        if($isFw==true){
            $sqlW = "update trade_dye_order set fhOver=1 where id='{$ckRes[0]['oId']}'";
            $this->_modelExample->execute($sqlW);
            //查看所有缸号的出库日期，取最大的那个
            $sqlbig = "SELECT c.dateCpck 
                         from chengpin_dye_cpck c
                         left join plan_dye_gang g on c.planId=g.id
                         left join trade_dye_order2ware w on g.order2wareId=w.id
                         left join trade_dye_order o on o.id=w.orderId
                         where o.id='{$ckRes[0]['oId']}' order by c.dateCpck desc limit 0,1";
            $dateCpckBig = $this->_modelExample->findBySql($sqlbig);
            //修改所有缸号的对账日期
            foreach ($wRes as $key => $value) {
                foreach ($value as $k => $vav) {
                    $sql="update plan_dye_gang set dateDuizhang1='{$dateCpckBig[0]['dateCpck']}' where id='{$vav['id']}'";
                    $this->_modelGang->execute($sql);
                }
            }
        }else{
            $sqlW = "update trade_dye_order set fhOver=0 where id='{$ckRes[0]['oId']}'";
            $this->_modelExample->execute($sqlW);
        }
    }
    /**
     * ps ：成品出库单打印（新）
     * Time：2017年12月4日 10:26:34
     * @author zcc
     * @param 参数类型
     * @return 返回值类型
    */
    function actionPrint(){
        //需要的引用model
        $modelOrder2Ware = & FLEA::getSingleton('Model_Trade_Dye_Order2Ware');
        $modelOrder = & FLEA::getSingleton('Model_Trade_Dye_Order');
        $p = $_POST[printId] ? $_POST : $_GET;
        // dump(count($p['printId']));die;
        //存在出库单号的情况，判断出库单号是否一致，不一致就返回报错
        if(count($p['printId'])>1){
             $chukuCodeFirst = $this->_modelExample->find($p['printId'][0]);
             foreach ($p['printId'] as $key => &$values) {
                $chukuCode = $this->_modelExample->find($values);
                // if($chukuCode['chukuCode']=='') continue; //如果都为空，则跳过，说明是老数据
                if($chukuCode['chukuCode']!=$chukuCodeFirst['chukuCode']){
                    js_alert('出库单号必须一致','window.close();window.opener.history.go()');
                }
             }
        }
        if($_POST['print']=='直接打印') {
            $this->actionPrintLodop();exit;
        }
        // dump($p['printId']);die;
        // dump($p);die;
        //找到出库单号下所有的出库id
        $sql="SELECT chukuCode FROM chengpin_dye_cpck WHERE id='{$p['printId'][0]}'";
        $chukuCodeNor = $this->_modelExample->findBySql($sql);
        // dump($chukuCodeNor);die;
        if($chukuCodeNor[0]['chukuCode']){
            $sql="SELECT id FROM chengpin_dye_cpck WHERE chukuCode='{$chukuCodeNor[0]['chukuCode']}'";
            $idsNew = $this->_modelExample->findBySql($sql);
            $idsNew = array_col_values($idsNew,'id');
            $p['printId'] = $idsNew;
        }
        // dump($p['printId']);die;
        $rowCpck=$this->_modelExample->findAllByPkvs($p[printId]);
        //先判断这打印的客户属于哪种结算方式 当为投料结算的时候 金额只有第一条出库的显示
        $sql = "SELECT c.paymentWay
            FROM trade_dye_order x 
            left join trade_dye_order2ware y on x.id=y.orderId 
            left join jichu_client c on c.id = x.clientId
            where y.id = '{$rowCpck[0]['Plan']['order2wareId']}'";
        $payment = $this->_modelExample->findBySql($sql);
        $paymentWay = $payment[0]['paymentWay'];
        //根据指定的键值对数组排序
        $rowCpck = array_column_sort($rowCpck,'planId');
        // dump($rowCpck);
        $arrCount = count($p[printId]);
        $j = 0;
        foreach($rowCpck as & $value) {
            for($i=0; $i<$arrCount; $i++) {
                if ($value[id] == $p[printId][$i])  {
                    $rowCpckPrint[$j] = $value;
                    $j++;
                }
            }
        }
        // dump($rowCpckPrint);die();
        if (count($rowCpckPrint))foreach($rowCpckPrint as & $value) {
            $value['cntChuku'] = $value['cntChuku'];
            $rowOrder2Ware = $modelOrder2Ware->findByField('id', $value[Plan][order2wareId]);
            $rowOrder = $modelOrder->findByField('id', $rowOrder2Ware[orderId]);
            //通用数据的赋值
            $value['orderCode'] = $rowOrder[orderCode];
            $value['kuanhao'] = $rowOrder2Ware['kuanhao'];
            $value['wareNameBc'] = $rowOrder2Ware['wareNameBc'];
            $value['vatNum'] = $value['Plan']['vatNum'];
            // 订单明细中写了纱支别名的时候 就显示别名
            $value['wareName'] =$rowOrder2Ware[Ware][guige].'||'.$rowOrder2Ware['Ware']['wareName'];
            $value['vatCode'] = $value['Plan']['vatId'];
            $value['color'] = $rowOrder2Ware['color'];
            $value['colorNum'] = $rowOrder2Ware['colorNum'];
            $value['colorSeCode'] = $rowOrder2Ware['color'].'/'.$rowOrder2Ware['colorNum'];
            $value['vatNum'] = $value['Plan']['vatNum'];
            $value['cntPlanTouliao'] = $value['Plan']['cntPlanTouliao'];
            $value['cntPlanTouliao2'] = $value['cntPlanTouliao'];
            $value['danjia'] = $rowOrder2Ware['danjia'];
            $value['zhelv'] = $rowOrder2Ware['zhelvMx']*100;
            $value['clientName'] = $rowOrder['Client']['fullName']?$rowOrder['Client']['fullName']:$rowOrder['Client']['compName'];
            // dump($paymentWay);die();
            if ($paymentWay==0) {//当结算方式为  投料数结算
                if ($value['danjia']>0) {
                    $value['money'] = round($value['danjia']*$value['cntPlanTouliao'],2);//单价*投料数
                }else{
                    $value['money'] = round($rowOrder2Ware['money'],2);//小缸价
                }
                
                //获取这个出库的 第一条数据
                $sql = "SELECT * 
                    FROM chengpin_dye_cpck  
                    where planId= '{$value['planId']}' order by id asc limit 0,1";
                $cpck = $this->_modelExample->findBySql($sql);
                if ($cpck[0]['id'] != $value['id']) {//当本条数据不等于第一条出库数据时
                    $value['money'] = ''; //让金额为空数据
                }
            }
            if ($paymentWay==1) {//当结算方式为  净重结算
                if ($value['danjia']>0) {
                    $value['money'] = round($value['danjia']*$value['jingKg'],2);//单价*净重
                }else{
                    $value['money'] = round($rowOrder2Ware['money'],2);//小缸价
                }
            }
            if ($paymentWay==2) {//当结算方式为  折率净重结算
                if ($value['danjia']>0) {
                    $value['money'] = round($value['danjia']*$value['jingKgZ'],2);//单价*折率净重
                }else{
                    $value['money'] = round($rowOrder2Ware['money'],2);//小缸价
                }
            }
            //重复的缸号 合计不叠加投料数
            if($tempVatNum!=$value[Plan][vatNum]) {
                $ifShow = 1;
                $tempVatNum=$value[Plan][vatNum];
            } else $ifShow = 0;
            if ($ifShow == 0) {//判断该条为重复缸号数据 
                $value['cntPlanTouliao2'] = 0;
            }
            //by zcc 2017年12月29日 13:14:49
            //(1)当为回修缸号时 打印时金额显示为空 投料数合计不进行叠加 
            //(2)当为回修缸号时 如果出现未出库整缸回修 标记 则金额显示,投料数合计进行叠加，否则如上
            //(3)当为回修缸号时 是未出库整缸回修 会出现回修多次的情况 最后一次才正在发货
            if ($value['Plan']['parentGangId']) {
                if ($value['Plan']['isHuixiuCk']!=1) {
                    $value['cntPlanTouliao2'] = 0;
                    if ($paymentWay=='0') {
                        $value['money'] = '';
                    }
                }else{//可能会用不到 提前设下机制
                    //获取同一原缸的所有未出库整缸回修
                    $sql = "SELECT id FROM plan_dye_gang 
                        WHERE parentGangId={$value['Plan']['parentGangId']} 
                        AND isHuixiuCk=1  order by id desc limit 0,1";
                    $LastHuixiu = $this->_modelExample->findBySql($sql);
                    if ($value['Plan']['id']!=$LastHuixiu[0]['id']) {
                        $value['cntPlanTouliao2'] = 0;
                        if ($paymentWay=='0') {
                            $value['money'] = '';
                        }
                    }   
                }
                
            }


            //合计项
            $tJingKg +=$value['jingKg'];
            $tCntPlanTouliao +=$value['cntPlanTouliao2'];
            $tCcntJian +=$value['cntJian'];
            $tCcntTongzi +=$value['cntTongzi'];
            $tMaoKg += $value['maoKg'];
            $tMoney += $value['money'];
            $cntChuKu += $value['cntChuku'];
        }
        $rowCpckPrint[$i]['vatNum'] = '<strong>合计</strong>';
        $rowCpckPrint[$i]['cntPlanTouliao'] = '<strong>'.$tCntPlanTouliao.'</strong>';
        $rowCpckPrint[$i]['jingKg'] = '<strong>'.$tJingKg.'</strong>';
        $rowCpckPrint[$i]['cntJian'] = '<strong>'.$tCcntJian.'</strong>';
        $rowCpckPrint[$i]['cntTongzi'] = '<strong>'.$tCcntTongzi.'</strong>';
        $rowCpckPrint[$i]['maoKg'] = '<strong>'.$tMaoKg.'</strong>';
        $rowCpckPrint[$i]['money'] = '<strong>'.$tMoney.'</strong>';
        $rowCpckPrint[$i]['cntChuku'] = '<strong>'.$cntChuKu.'</strong>';
        // dump($rowOrder['Client']['paymentWay']);die;
        $arrFieldInfo = array(
            // "orderCode" =>"订单号",
            "wareNameBc"=>'客户单号',
            "vatNum"    =>"缸号",
            'wareName'  =>'纱支/规格',
            'color'     =>'颜色',
            'kuanhao'   =>'本厂色号',
            'colorNum'  =>'客户色',
            "cntPlanTouliao" =>"投染数(kg)",
            "cntJian"   =>"件数",
            'jingKg'    =>'重量',
            'cntTongzi' =>"只数"
            // 'danjia'=>'染色单价',
            // 'money'=>'金额',
        );
        //dump($rowOrder['Client']);die;
        // if($rowOrder['Client']['paymentWay']=='0' && $rowOrder['Client']['compName']!='霍雅'&&$rowOrder['Client']['compName']!='香盈'){ //霍雅特殊，需要显示毛重和净重
        //  $arrFieldInfo = array(
        //      // "orderCode" =>"订单号",
        //      "vatNum" =>"缸号",
        //      'wareName' => '纱支规格',
        //      'colorSeCode' =>'色号/色别',
        //      "kuanhao" =>"款号",
        //      "cntJian"=>"件数",
        //      "cntPlanTouliao" =>"投染数(kg)",
        //      "cntChuku"=>"出库数量",
        //      // 'danjia'=>'染色单价',
        //      // 'money'=>'金额',
        //  );
        // }
        // if ($rowOrder['Client']['paymentWay']=='2') {
        //  $arrFieldInfo = array(
        //      // "orderCode" =>"订单号",
        //      "vatNum" =>"缸号",
        //      'wareName' => '纱支规格',
        //      'colorSeCode' =>'色号/色别',
        //      "kuanhao" =>"款号",
        //      "cntJian"=>"件数",
        //      "color" =>"颜色",
        //      "cntPlanTouliao" =>"投染数(kg)",
        //      "maoKg"=>"毛重(kg)",
        //      'jingKgZ'=>'计价重(kg)',
        //      'zhelv' =>'损率',
        //      // 'danjia'=>'染色单价',
        //      // 'money'=>'金额',
        //  );
        // }
        $mphone = & FLEA::getSingleton('Model_Sys_CompInfo');
        $Phone=$mphone->findAll();
        //将打印的信息保存到打印日志中
        $date=date("Y-m-d");
        $user=$_SESSION['REALNAME'];
        $cpckCode=$this->getNewCpckCode();
        $log = $arr = $printTemp = array();
        $log = array(
            'datePrint'=>date("Y-m-d"),
            'user'=>$user,
            'cpckCode'=>$cpckCode,
        );
        foreach($_POST['printId'] as & $v){
            $cpckId=$v;
            $cpckInfo = $this->_modelExample->find($v,null,'*',false);
            $details = $cpckInfo?json_encode($cpckInfo):'';
            $arr = array(
                'cpckId'=>$cpckId,
                'details'=>$details,
            );
            $printTemp[] = $arr;
        }
        $log['Blog'] = $printTemp;
        if($printTemp){
            $this->_modelPrintLog->save($log);
        }
        $smarty = & $this->_getView();
        $smarty->assign('arr_field_info',$arrFieldInfo);
        $smarty->assign("arr_field_value",$rowCpckPrint);
        $smarty->assign("phone",$Phone);
        $smarty->assign("cpckcode",$cpckCode);
        $smarty->assign('fahuoren', $_SESSION[REALNAME]);
        $smarty->display('Chengpin/Dye/CpckPrint.tpl');
    }

    //成品出库单利用lodop控件打印
    function actionPrintLodop() {
        $perPage = 10;//每页的行数
        $ret = array();
        $ret['title'] = FLEA::getAppInf('compName');
        $ret['memo'] = "";
        //dump($_POST);exit;
        //echo(count($_POST[printId])); exit;
        $p = $_POST[printId] ? $_POST : $_GET;
        if(count($p['printId'])>1){
             $chukuCodeFirst = $this->_modelExample->find($p['printId'][0]);
             foreach ($p['printId'] as $key => &$values) {
                $chukuCode = $this->_modelExample->find($values);
                //if($chukuCode['chukuCode']=='') continue; //如果都为空，则跳过，说明是老数据
                if($chukuCode['chukuCode']!=$chukuCodeFirst['chukuCode']){
                    js_alert('出库单号必须一致','window.close();window.opener.history.go()');
                }
             }
        }
        //dump($p);exit;
        $modelOrder2Ware = & FLEA::getSingleton('Model_Trade_Dye_Order2Ware');
        $modelOrder = & FLEA::getSingleton('Model_Trade_Dye_Order');
        $mGang = & FLEA::getSingleton("Model_Plan_Dye_Gang");
        //$mClient = & FLEA::getSingleton("Model_Jichu_Client");
        //找到出库单号下所有的出库id
        $sql="SELECT chukuCode FROM chengpin_dye_cpck WHERE id='{$p['printId'][0]}'";
        // dump($sql);die;
        $chukuCodeNor = $this->_modelExample->findBySql($sql);
        // dump($chukuCodeNor);die;
        if($chukuCodeNor[0]['chukuCode']){
            $sql="SELECT id FROM chengpin_dye_cpck WHERE chukuCode='{$chukuCodeNor[0]['chukuCode']}'";
            $idsNew = $this->_modelExample->findBySql($sql);
            $idsNew = array_col_values($idsNew,'id');
            $p['printId'] = $idsNew;
        }
        $rowCpck=$this->_modelExample->findAllByPkvs($p['printId']);
        $rowCpck = array_column_sort($rowCpck,'planId');
        // dump($rowCpck);die();
        $tempVatNum='';
        if($rowCpck) foreach($rowCpck as & $v) {
            $temp = $mGang->formatRet($v['Plan']);
            $v['Plan'] = $temp;
            //判断这个出库数据结算方式 s算出金额 by zcc 2017年10月27日 14:01:22
            // 按照投料数的字段有：投料数，毛重，净重;金额=投料数*单价
            // 按照净重的字段：投料数，毛重，净重；金额=净重*单价
            // 按照折率的字段：净重，计价重（折率净重）；金额=计价重*单价
            $paymentWay = $temp['Client']['paymentWay'];
            $money = 0 ;
            if ($paymentWay=='0') {//投料
                if ($temp['OrdWare']['danjia']>0) {
                    $money = round($temp['cntPlanTouliao']*$temp['OrdWare']['danjia'],2);
                }else{
                    $money = round($temp['OrdWare']['money'],2);
                }
                
                //获取这个出库的 第一条数据
                $sql = "SELECT * 
                    FROM chengpin_dye_cpck  
                    where planId= '{$v['planId']}' order by id asc limit 0,1";
                $cpck = $this->_modelExample->findBySql($sql);
                if ($cpck[0]['id'] != $v['id']) {//当本条数据不等于第一条出库数据时
                    $money = ''; //让金额为空数据
                }
            }
            if ($paymentWay=='1') {//净重
                if ($temp['OrdWare']['danjia']>0) {
                    $money = round($v['jingKg']*$temp['OrdWare']['danjia'],2);
                }else{
                    $money = round($temp['OrdWare']['money'],2);
                }
            }
            if ($paymentWay=='2') {//折率净重
                if ($temp['OrdWare']['danjia']>0) {
                    $money = round($v['jingKgZ']*$temp['OrdWare']['danjia'],2);
                }else{
                    $money = round($temp['OrdWare']['money'],2);
                }
                
            }
            // dump($temp);die();
            if($tempVatNum!=$v[Plan][vatNum]) {
                $ifShow = 1;
                $tempVatNum=$v[Plan][vatNum];
            } else $ifShow = 0;
            if ($ifShow == 0) {//判断该条为重复缸号数据 
                $v['cntPlanTouliao2'] = 0;
            }else{
                $v['cntPlanTouliao2'] = $temp['cntPlanTouliao'];
            }


            //by zcc 2017年12月29日 13:14:49
            //(1)当为回修缸号时 打印时金额显示为空 投料数合计不进行叠加 
            //(2)当为回修缸号时 如果出现未出库整缸回修 标记 则金额显示,投料数合计进行叠加，否则如上
            //(3)当为回修缸号时 是未出库整缸回修 会出现回修多次的情况 最后一次才正在发货
            if ($temp['parentGangId']) {
                if ($temp['isHuixiuCk']!=1) {
                    $v['cntPlanTouliao2'] = 0;
                    if ($paymentWay=='0') {
                        $money = '';
                    }
                }
                else{//可能会用不到 提前设下机制(防止多次回修的数据有出库记录)
                    //获取同一原缸的所有未出库整缸回修
                    $sql = "SELECT id FROM plan_dye_gang 
                        WHERE parentGangId={$temp['parentGangId']} 
                        AND isHuixiuCk=1  order by id desc limit 0,1";
                    $LastHuixiu = $this->_modelExample->findBySql($sql);
                    if ($temp['id']!=$LastHuixiu[0]['id']) {
                        $v['cntPlanTouliao2'] = 0;
                        if ($paymentWay=='0') {
                            $money = '';
                        }
                    }   
                }
                
            }
            $ret['Gang'][] = array(
                "orderCode" => $temp['OrdWare']['Order']['orderCode'],
                "wareNameBc" => $temp['OrdWare']['wareNameBc'],
                "vatNum" =>$temp['vatNum'],
                'wareName' =>$temp['OrdWare']['Ware']['guige'].' '.$temp['OrdWare']['Ware']['wareName'],
                'chandi' => $temp['OrdWare']['chandi'],
                "colorNum" =>$temp['OrdWare']['colorNum'],
                "kuanhao" =>$temp['OrdWare']['kuanhao'],
                "color" =>$temp['OrdWare']['color'],
                "cntPlanTouliao" =>$temp['cntPlanTouliao'],
                "cntPlanTouliao2" =>$v['cntPlanTouliao2'],
                "cntChuku"=>$v['cntChuku'],
                "jingKg"=>$v['jingKg'],
                "cntJian"=>$v['cntJian'],
                "cntTongzi"=>$v['cntTongzi'],
                'memo'=>$v['memo'],
                'danjia' =>$temp['OrdWare']['money']==0?$temp['OrdWare']['danjia']:'',//新增 染色单价
                'colorSeCode' =>$temp['OrdWare']['color'].'/'.$temp['OrdWare']['colorNum'],//打印界面的 色号/色别组合
                'kindName' => $temp['OrdWare']['Order']['kind']=='0'?'加工':'经销',//类别
                "jingKgZ"=>$v['jingKgZ'],//折率净重 对应的打印 计价重
                'zhelv'=>$temp['OrdWare']['zhelvMx']*100,//折率 化成 百分比
                'moneyFs' =>$money,
                "maoKg"=>$v['maoKg'],
            );
        }
        // dump($rowCpck);exit;
        $ret['Client'] = $rowCpck[0]['Plan']['Client'];
        $ret['dateCpck'] = $rowCpck[0]['dateCpck'];
        $ret['chukuCode'] = $rowCpck[0]['chukuCode'];
        $ret['clientName'] = $ret['Client']['fullName']?$ret['Client']['fullName']:$ret['Client']['compName'];
        //dump($ret);exit;
        $ret['datePint'] = date('Y-m-d');
        $ret['senderName'] = $rowCpck[0]['creater']?$rowCpck[0]['creater']:$_SESSION[REALNAME];
        $ret['timeInput'] = $rowCpck[0]['dt'];
        $str="select * from sys_setup where setName='PrintCpck'";
        $query=mysql_query($str);
        $re=mysql_fetch_assoc($query);
        if($re['setValue']=='PrintCpck.js'){
            $cntPlanTouliao2 = $this->getHeji1($ret['Gang'],array('cntPlanTouliao2'),'vatNum');
            $heji = $this->getHeji1($ret['Gang'],array('cntPlanTouliao','cntChuku','jingKg','cntJian','cntTongzi','jingKgZ','moneyFs','maoKg'),'vatNum');
            $heji['cntPlanTouliao'] = $cntPlanTouliao2['cntPlanTouliao2'];
        }else{
            $cntPlanTouliao2 = $this->getHeji1($ret['Gang'],array('cntPlanTouliao2'),'vatNum');
            $heji = $this->getHeji1($ret['Gang'],array('cntPlanTouliao','cntChuku','jingKg','cntJian','cntTongzi','jingKgZ','moneyFs','maoKg'),'vatNum');
            $heji['cntPlanTouliao'] = $cntPlanTouliao2['cntPlanTouliao2'];
        }
        $ret['Gang'][] = $heji;
        $cnt = ceil(count($ret['Gang'])/$perPage);

        $gangs = $ret['Gang'];
        //dump($cnt);dump($gangs);exit;
        for($i=0;$i<$cnt;$i++) {
            $temp = $ret;
            $temp['Gang'] = array_slice($gangs,$i*$perPage,$perPage);
            $r[] = $temp;
            unset($temp);
        }
        // dump($r);exit;
        //dump($rowCpck[0]);exit;
        //将打印的信息保存到打印日志中
        if(!$_POST['cpckcode']) {//post中没有cpckCode说明是直接打印，需要记录日志
            $date=date("Y-m-d");
            $user=$_SESSION['REALNAME'];
            $cpckCode=$this->getNewCpckCode();
            $log = $arr = $printTemp = array();
            $log = array(
                'datePrint'=>date("Y-m-d"),
                'user'=>$user,
                'cpckCode'=>$cpckCode,
            );
            foreach($p['printId'] as & $v){
                $cpckId=$v;
                $cpckInfo = $this->_modelExample->find($v,null,'*',false);
                $details = $cpckInfo?json_encode($cpckInfo):'';
                $arr = array(
                    'cpckId'=>$cpckId,
                    'details'=>$details,
                );
                $printTemp[] = $arr;
            }
            $log['Blog'] = $printTemp;
            if($printTemp){
                $this->_modelPrintLog->save($log);
            }
        }
        if($r)foreach($r as & $v){
            //$v['compName'] = $r[0]['title'];
            foreach($v['Gang'] as  $key=> & $vv){
                $len=strlen($vv['colorNum']);
                if($len>=11){
                    $s=substr($vv['colorNum'],-12);
                    $vv[colorNum]=$s;
                }
                if($_POST['cpckcode']){
                    $v['cpckcode']=$_POST['cpckcode'];
                }else{
                     $v['cpckcode']=$cpckCode;
                }
            }
            $v['cpckcode'] = $v['chukuCode']?$v['chukuCode']:$v['cpckcode'];
            $v['employName'] = $v['Client']['Trader']['employName']?$v['Client']['Trader']['employName']:'';
        }
        $smarty = & $this->_getView();
        //$smarty->assign('arr_field_info',$arrFieldInfo);
        // dump($r);die;
        $smarty->assign("obj",$r);

        $servTel = $this->getServTel();
        $smarty->assign("tel",$servTel);
        //$smarty->assign('fahuoren', $_SESSION[REALNAME]);
        // if ($paymentWay=='2') {// 为结算方式为折率净重时 走专用模版
        //  $smarty->display('Chengpin/Dye/PrintDirectlyTwo.tpl');
        //  die;
        // }
        // if($paymentWay=='0' && $r[0]['Client']['compName']!='霍雅' && $r[0]['Client']['compName']!='香盈'){
        //  $smarty->display('Chengpin/Dye/PrintDirectlyThree.tpl');
        //  die;
        // }
        $smarty->display('Chengpin/Dye/PrintDirectly.tpl');
    }
    
     //自动获取出库单号
    function getNewCpckCode() {
                $str="select * from chengpin_printblog";
                $str.=" order by id desc";
                $query=mysql_query($str);
                $re=mysql_fetch_assoc($query);
        $max = $re['cpckCode'];
        $temp = date("ym")."001";
        if ($temp>$max){
                    return $temp;
                }else{
                     $a = substr($max,-3)+1;
                     if($a<10){
                         return substr($max,0,6).$a;
                     }elseif($a<=99){
                         return substr($max,0,5).$a;
                     }else{
                         return substr($max,0,4).$a;
                     }
                }
    }

    function actionRemoveByAjax(){
        // dump($_POST);die;
        //删除出库明细数据
        if($_POST['id']>0){
            $sql="SELECT * FROM chengpin_dye_cpck WHERE id='{$_POST['id']}'";
            $plan = $this->_modelExample->findBySql($sql);
            $sql="SELECT * FROM chengpin_dye_cpck WHERE planId='{$plan[0]['planId']}' AND id<>'{$_POST['id']}' AND memo='已发完'";//如果存在已发完的出库数据，那么不需要把fhWc变为0，反之需要
            $ckA = $this->_modelExample->findBySql($sql);
            if(!$ckA){
                $sql="update plan_dye_gang set fhWc=0 WHERE id='{$plan[0]['planId']}'";
                $this->_modelExample->execute($sql);
                //找到orderid,订单表需要把fhOver改为0
                $sql="SELECT o.id as orderId 
                         FROM plan_dye_gang g
                         LEFT JOIN trade_dye_order2ware w on g.order2wareId=w.id
                         LEFT JOIN trade_dye_order o on o.id=w.orderId
                         WHERE g.id='{$plan[0]['planId']}'
                ";
                $orderId = $this->_modelExample->findBySql($sql);
                $sql="update trade_dye_order set fhOver=0 WHERE id='{$orderId[0]['orderId']}'";
                $this->_modelExample->execute($sql);
            }
            $sql="delete from chengpin_dye_cpck WHERE id='{$_POST['id']}'";
            $this->_modelExample->execute($sql);
            //修改码单chukuid为0
            $sql="update dye_db_chanliang_mx set chukuId=0 WHERE chukuId='{$_POST['id']}'";
            $r = $this->_modelExample->execute($sql);
            if (!$r) {
                $arr = array('success' => false, 'msg' => '删除失败');
                echo json_encode($arr);
                exit;
            }
            $arr = array('success' => true);
            echo json_encode($arr);
            exit;
        }
    }

    function actionRemove(){
        // dump($_GET);die;
        // 删除该出库单号下的所有出库数据
        $chuku = $this->_modelExample->find($_GET['id']);
        $chukuCode = $chuku['chukuCode'];
        $chukuArr = $this->_modelExample->findAll(array('chukuCode'=>$chukuCode));
        foreach ($chukuArr as $key => $value) {
            $sql="SELECT * FROM chengpin_dye_cpck WHERE id='{$value['id']}'";
            $plan = $this->_modelExample->findBySql($sql);
            $sql="SELECT * FROM chengpin_dye_cpck WHERE planId='{$plan[0]['planId']}' AND id<>'{$value['id']}' AND memo='已发完'";//如果存在已发完的出库数据，那么不需要把fhWc变为0，反之需要
            $ckA = $this->_modelExample->findBySql($sql);
            if(!$ckA){
                $sql="update plan_dye_gang set fhWc=0 WHERE id='{$plan[0]['planId']}'";
                $this->_modelExample->execute($sql);
                //找到orderid,订单表需要把fhOver改为0
                $sql="SELECT o.id as orderId 
                         FROM plan_dye_gang g
                         LEFT JOIN trade_dye_order2ware w on g.order2wareId=w.id
                         LEFT JOIN trade_dye_order o on o.id=w.orderId
                         WHERE g.id='{$plan[0]['planId']}'
                ";
                $orderId = $this->_modelExample->findBySql($sql);
                $sql="update trade_dye_order set fhOver=0 WHERE id='{$orderId[0]['orderId']}'";
                $this->_modelExample->execute($sql);
            }
            //end
            $sql="delete from chengpin_dye_cpck WHERE id='{$value['id']}'";
            $this->_modelExample->execute($sql);
            $sql="update dye_db_chanliang_mx set chukuId=0 WHERE chukuId='{$value['id']}'";
            $this->_modelExample->execute($sql);
        }
        redirect($this->_url('RightMd'));
    }

    //码单信息显示
    function actionMadanInfo(){
        $sql =" select j.wareName,j.guige,w.color,w.colorNum,g.vatNum,g.cntPlanTouliao,w.orderId,d.dateInput,d.gangId,e.perName,d.workerCode
                from dye_db_chanliang_mx m 
                left join dye_db_chanliang d on m.chanliangId=d.id
                left join plan_dye_gang g on d.gangId=g.id
                left join trade_dye_order2ware w on w.id=g.order2wareId
                left join jichu_ware j on j.id=w.wareId
                left join jichu_gxperson e on e.workerCode=d.workerCode
                where 1 and m.chukuId='{$_GET['id']}'";
        $rowset = $this->_modelExample->findBySql($sql);
        // dump($rowset);die;
        foreach ($rowset as $key => &$value) {
            $sqlCn = "select jj.compName,jj.compCode 
                      from trade_dye_order t 
                      left join jichu_client jj on t.clientId=jj.id
                      where t.id='{$value['orderId']}'";
            $clientName = $this->_modelExample->findBySql($sqlCn);
            $value['compName'] = $clientName[0]['compName'];
            $value['compCode'] = $clientName[0]['compCode'];
            $sqlMadan ="select * from dye_db_chanliang_mx where gangId='{$value['gangId']}' and chukuId='{$_GET['id']}'";
            $madans = $this->_modelExample->findBySql($sqlMadan);

        }
        $jingzhong =0;
        $maozhong = 0;
        $cntTongzi =0;
        foreach ($madans as $key => $val) {
            $cntTongzi +=$val['cntTongzi'];
            $jingzhong+=$val['jingzhong'];
            $maozhong+=$val['maozhong'];
        }
       
        $counts = count($madans);
        $row = $rowset[0];
        //构建一个20的数组
        $temp = array();
        for($i=0;$i<20;$i++){
            $temp[] = array();
        }
        $temp1 = array();
        for($j=0;$j<20;$j++){
            $temp1[] = array();
        }
        $madanNew = array();
        foreach ($madans as $key => &$vv) {
            $madanNew[$key+1] = $madans[$key];
        }
        // dump($row);die;
        // dump($madanNew);die;
        $perPage = 60;
        $cnt = ceil(count($madanNew)/$perPage);
        $tempArr = array();
        for($i=0;$i<$cnt;$i++){
           $tempArr[] = array_slice($madanNew,$i*$perPage,$perPage);
        }
        $tt = array();
        foreach ($tempArr as $key => &$vals) {
            foreach ($vals as $ke => &$vall) {
                $tt[$key][$ke+1] = $vals[$ke];
            }
        }
        $MdcompName=& FLEA::getAppInf('MdCompName');
        $smarty=$this->_getView();
        $smarty->assign('aRow',$row);
        $smarty->assign('info',$tt);
        $smarty->assign('counts',$counts);
        $smarty->assign('temp',$temp);
        $smarty->assign('temp1',$temp1);
        $smarty->assign('MdcompName',$MdcompName);
        $smarty->assign('cntTongziAll',$cntTongzi);
        $smarty->assign('jingzhongAll',$jingzhong);
        $smarty->assign('maozhongAll',$maozhong);
        $smarty->display('Chejian/madanDabao.tpl');

    }

    //新增订单明细，此订单明细是包含发外订单明细
    function actionGetMinxiByPlanId() {
        $planId = $_POST['planId'];
        if(!$planId) {
            echo json_encode(array('success'=>false,'msg'=>'缸号为空'));
            exit;
        }
        $planId = implode(',', $planId);
        //查找码单信息
        $sql = "SELECT y.vatNum,z.orderId,z.id as ord2proId,z.wareId,y.id
                from plan_dye_gang y
                LEFT JOIN trade_dye_order2ware z on y.order2wareId=z.id
                LEFT JOIN trade_dye_order a ON z.orderId=a.id
                where 1 and y.id in ({$planId})";
        $res = $this->_modelExample->findBySql($sql);
        // dump($sql);exit;
        foreach ($res as $key => & $v) {
            $gangInfo = $this->_modelGang->find($v['id']);
            $v['color'] = $gangInfo['OrdWare']['color'];
            $v['colorNum'] = $gangInfo['OrdWare']['colorNum'];
            // $orderInfo = $this->_modelOrder->find($v['orderId']);
            $orderSon = $this->_modelOrder2Ware->find($v['ord2proId']);
            $v['orderCode'] = $orderSon['Order']['orderCode'];
            $v['proName'] = $orderSon['Ware']['wareName'].' '.$orderSon['Ware']['guige'];
        }
        //查询
        echo json_encode(array('success'=>true,'res'=>$res));
        exit;
    }
}

?>